let messageMethod = require("../dao/messageListDAO").messageMethod;

// 新增留言
exports.addMessage = function (req, res){
  let newMessage = {
    userName: req.body.userName,
    phoneNumber: req.body.phoneNumber,
    email: req.body.email,
    message: req.body.message
  };
  messageMethod.save(newMessage, function (err){
    if(!err){
      res.send({
        code: 200,
        msg: "留言成功！"
      });
    }else{
      res.send({
        code: 201,
        msg: "留言失败！"
      });
    }
  })
};


// 获取留言列表
exports.getMessageList = function (req, res){
  messageMethod.findAll(function (err, doc) {
    if(!err){
      res.send({
        code: 200,
        data: doc,
        msg: "查询成功！"});
    }
    else{
      res.send({
        code: 201,
        msg: "查询失败！"});
    }
  })
};

// 删除
exports.delMessage = function (req, res){
  let id = req.body.id
  // 根据id查询单条数据
  messageMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      let par = {
        _id: id
      }
      // 删除单条数据
      messageMethod.remove(par,function (err, doc) {
        if(!err){
          res.send({
            code: 200,
            msg: "删除成功！"});
        }else{
          res.send({
            code: 200,
            msg: "删除失败！"});
        }
      })
    }
  })
};

// 修改
exports.editMessage = function (req, res) {
  let newMessage = {userName: req.body.userName, phoneNumber: req.body.phoneNumber, email: req.body.email, message: req.body.message};

  // 查询单个数据
  messageMethod.findOne({_id: req.body.id},function (err, doc) {
    if(!err && doc){
      // 更新单个数据
      messageMethod.update({'_id':req.body.id},newMessage,function (err) {
        if(!err){
          res.send({
            code: 200,
            msg: "修改成功！"});
        }
        else{
          res.send({
            code: 201,
            msg: "修改失败！"});
        }
      })
    }
  })
}
